package com.team06.util;

import com.team06.pojo.Poke;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PokeXmlParserUtil {
    private static final Logger LOGGER = Logger.getLogger(PokeXmlParserUtil.class.getName());

    public static Poke parseXml(String xmlPath) {
        Poke entity = new Poke();
        try {
            File file = new File(xmlPath);
            SAXBuilder saxBuilder = new SAXBuilder();
            Document document = saxBuilder.build(file);
            Element root = document.getRootElement();

            // 解析 META 节点
            Element metaElement = root.getChild("META");
            if (metaElement != null) {
                entity.setMetaSnDR(getChildTextSafe(metaElement, "SNDR"));
                entity.setMetaRCVR(getChildTextSafe(metaElement, "RCVR"));
                String seqnText = getChildTextSafe(metaElement, "SEQN");
                if (seqnText != null) {
                    entity.setMetaSEQN(Integer.parseInt(seqnText));
                }
                entity.setMetaDDTM(getChildTextSafe(metaElement, "DDTM"));
                entity.setMetaTYPE(getChildTextSafe(metaElement, "TYPE"));
                entity.setMetaSTYP(getChildTextSafe(metaElement, "STYP"));
            }

            // 解析 DFLT 节点
            Element dfltElement = root.getChild("DFLT");
            if (dfltElement != null) {
                entity.setDfltFLID(getChildTextSafe(dfltElement, "FLID"));
                entity.setDfltFFID(getChildTextSafe(dfltElement, "FFID"));
                entity.setDfltFIDE(getChildTextSafe(dfltElement, "FIDE"));
                entity.setDfltFATT(getChildTextSafe(dfltElement, "FATT"));
                entity.setDfltSTAT(getChildTextSafe(dfltElement, "STAT"));
                entity.setDfltISTA(getChildTextSafe(dfltElement, "ISTA"));
                entity.setDfltMSTA(getChildTextSafe(dfltElement, "MSTA"));
                entity.setDfltMIST(getChildTextSafe(dfltElement, "MIST"));
                entity.setDfltPAST(getChildTextSafe(dfltElement, "PAST"));
                entity.setDfltELDT(getChildTextSafe(dfltElement, "ELDT"));
                entity.setDfltPOKT(getChildTextSafe(dfltElement, "POKT"));
                entity.setDfltMPOK(getChildTextSafe(dfltElement, "MPOK"));
            }

        } catch (JDOMException | IOException | NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Failed to parse XML file: " + xmlPath, e);
            return null;
        }
        return entity;
    }

    private static String getChildTextSafe(Element parent, String childName) {
        Element child = parent.getChild(childName);
        return child != null ? child.getText() : null;
    }
}